package com.wjk.cms.controller;

import com.alibaba.fastjson.JSONObject;
import com.wjk.cms.common.AppType;
import com.wjk.cms.common.Result;

import com.wjk.cms.pojo.*;
import com.wjk.cms.service.CardService;
import com.wjk.cms.service.OrderService;
import com.wjk.cms.service.UserService;
import com.wjk.cms.util.CommonUtil;
import com.wjk.cms.util.sms.SmsUtil;
import com.wjk.cms.util.wx.WxConfig;
import com.wjk.cms.util.wx.WxPayUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author WUGN
 * @des
 * @date 2021/9/13 15:50
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController extends AuthenticatedController{

    @Autowired
    private OrderService orderService;

    @Autowired
    private CardService cardService;

    @Autowired
    private UserService userService;




    @PostMapping("/active")
    public Result place(
            @RequestParam("cardId") Long cardId
    ){
       /* User currentUser = getCurrentUser();
        Order order = new Order();
        order.setCardId(cardId);
        order.setStatus(0);
        order.setUserId(currentUser.getId());
        order.setAmount(paymoney);
        order.setCode(CommonUtil.generateOrderCode());*/
        return Result.ok();
    }



    @PostMapping("/list")
    public Result list(
            @RequestParam(value = "type",required = false) String type,
            @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo, // 页码
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize // 数量
    ){
        User currentUser = getCurrentUser();
        if(!currentUser.getType().equals("0")){
            return Result.error("非经销商无权进行操作");
        }
        List<Order> orders = orderService.find(currentUser.getId()+"", type, pageNo, pageSize);

        return Result.ok().add("data",orders);
    }

    @PostMapping("/customerOrderlist")
    public Result customerOrderlist(
            @RequestParam(value = "keywords", required = false) String keywords,
            @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo, // 页码
            @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize // 数量
    ){
        User currentUser = getCurrentUser();
        if(!currentUser.getType().equals("0")){
            return Result.error("非客户无权进行操作");
        }
        List<Order> orders = orderService.customerOrderlist(currentUser.getId()+"",keywords,  pageNo, pageSize);

        return Result.ok().add("data",orders);
    }


    private HashMap formatPriceStr(String price){
        HashMap<String, String> map = new HashMap<>();
        String[] split = price.split(",");
        for (String s : split) {
            String[] id_price = s.split(":");
            map.put(id_price[0],id_price[1]);
        }
        return map;
    }

    /**
     * 微信小程序支付
     */
    @PostMapping({"/pay-with-wx-xcx", "/cardActive"})
    public Result payWithWxXcx(
            HttpServletRequest request,
            @RequestParam("cardCode") String cardCode
    ) {


        User currentUser = getCurrentUser();
        if(!currentUser.getType().equals("2")){
            return Result.error("非经销商没有权限操作");
        }
        User parent = userService.findById(currentUser.getParentId());
        Card card = cardService.getByCode(cardCode);
        if(card==null){
            return Result.error("卡不存在");
        }
        if(card.getUserId()!=currentUser.getId()){
            return Result.error("没有权限激活该卡");
        }
        if(card.getStatus()!=1){
            return Result.error("非领取状态不能激活");
        }
        String paymoney = card.getCategory().getSellerPrice();


        String amount2 = card.getCategory().getChannelPrice();

        if(StringUtils.isNotBlank(currentUser.getPrice())){
            HashMap<String,String> hashMap = formatPriceStr(currentUser.getPrice());
            String strId= card.getCategoryId()+"";
            if(hashMap.containsKey(strId)){
                paymoney = hashMap.get(strId);
            }
        }

        if(parent!=null && StringUtils.isNotBlank(parent.getPrice())){
            HashMap<String,String> hashMap = formatPriceStr(parent.getPrice());
            String strId= card.getCategoryId()+"";
            if(hashMap.containsKey(strId)){
                amount2 = hashMap.get(strId);
            }
        }


        String orderCode = CommonUtil.generateOrderCode();

        JSONObject attachData = new JSONObject();
        attachData.put("user_id",currentUser.getId());
        attachData.put("order_code", orderCode);
        attachData.put("card_id", card.getId());
        attachData.put("amount1", paymoney);
        attachData.put("amount2", amount2);


//        return Result.ok();
        try {

            String openid = currentUser.getWxXcxOpenid(); // 业务数据
            String appid = WxConfig.APP_ID();
            String mch_id = WxConfig.MCH_ID(); // 租户配置
            String nonce_str = CommonUtil.generateNonceStr();
            String device_info = "wjk"; // 租户配置
            String body = "王浆卡"; // 业务参数
            String attach = attachData.toString(); // 业务数据
            String out_trade_no = orderCode;
            String moneyInFen = CommonUtil.getMoneyInFen(paymoney);
            String spbill_create_ip = request.getRemoteAddr();
            String notify_url = CommonUtil.getBaseUrl(request) + "/auth/pay/notify/wx";
            String trade_type = WxConfig.TRADE_TYPE_XCX();

            SortedMap<String, String> packageParams = new TreeMap<>();
            packageParams.put("appid", appid);
            packageParams.put("mch_id", mch_id);
            packageParams.put("nonce_str", nonce_str);
            packageParams.put("device_info", device_info);
            packageParams.put("body", body);
            packageParams.put("attach", attach);
            packageParams.put("out_trade_no", out_trade_no);
            packageParams.put("total_fee", moneyInFen);
            packageParams.put("spbill_create_ip", spbill_create_ip);
            packageParams.put("notify_url", notify_url);
            packageParams.put("trade_type", trade_type);
            packageParams.put("openid", openid);
            String sign = WxPayUtil.createPackageSign(packageParams);

            String xml = "<xml>"
                    + "<appid>" + appid + "</appid>"
                    + "<mch_id>" + mch_id + "</mch_id>"
                    + "<device_info>" + device_info + "</device_info>"
                    + "<nonce_str>" + nonce_str + "</nonce_str>"
                    + "<sign>" + sign + "</sign>"
                    + "<body><![CDATA[" + body + "]]></body>"
                    + "<attach><![CDATA[" + attach + "]]></attach>"
                    + "<out_trade_no>" + out_trade_no + "</out_trade_no>"
                    + "<total_fee>" + moneyInFen  + "</total_fee>"
                    + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"
                    + "<notify_url>" + notify_url + "</notify_url>"
                    + "<trade_type>" + trade_type + "</trade_type>"
                    + "<openid>" + openid + "</openid>"
                    + "</xml>";
            try {
                String prepayId = WxPayUtil.unifiedOrder(xml).get("prepay_id");
                if (StringUtils.isEmpty(prepayId)) {
                    return Result.error("微信统一下单接口出错");
                } else {
                    String timestamp = CommonUtil.getTimeStamp();
                    String packageStr = "prepay_id=" + prepayId;

                    List<NameValuePair> signParams = new LinkedList<>();
                    signParams.add(new BasicNameValuePair("appId", appid));
                    signParams.add(new BasicNameValuePair("nonceStr", nonce_str));
                    signParams.add(new BasicNameValuePair("package", packageStr));
                    signParams.add(new BasicNameValuePair("signType", "MD5"));
                    signParams.add(new BasicNameValuePair("timeStamp", timestamp));
                    String paySign = WxPayUtil.createPaySign(signParams);

                    // 带到预支付页面的参数值
                    JSONObject data = new JSONObject();
                    data.put("nonceStr", nonce_str);
                    data.put("timeStamp", timestamp);
                    data.put("package", packageStr);
                    data.put("paySign", paySign);
                    data.put("signType", WxConfig.SIGN_TYPE());

                    log.info("带到预支付页面的参数值:" + data.toString());
                    return Result.ok().add("payorder", data);
                }
            } catch (Exception e1) {
                log.error(e1.getMessage(), e1);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return Result.error("微信支付订单出错");
    }



}
